package com.jz.main.io.nio;

import java.util.ArrayList;
import java.util.HashMap;

public class MergeSort {
    public static void mergeSort(int[] arr) {
        if (arr.length <= 1) {
            return;
        }

        int mid = arr.length / 2;
        int[] left = new int[mid];
        int[] right = new int[arr.length - mid];

        System.arraycopy(arr, 0, left, 0, mid);
        System.arraycopy(arr, mid, right, 0, arr.length - mid);
        mergeSort(left);
        mergeSort(right);
        merge(arr, left, right);
    }

    private static void merge(int[] arr, int[] left, int[] right) {
        int i = 0, j = 0, k = 0;

        while (i < left.length && j < right.length) {
            if (left[i] <= right[j]) {
                arr[k++] = left[i++];
            } else {
                arr[k++] = right[j++];
            }
        }
        while (i < left.length) {
            arr[k++] = left[i++];
        }

        while (j < right.length) {
            arr[k++] = right[j++];
        }
    }

    private static void sys(int[] arr){
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }

    public static void main(String[] args) {
//        int[] array = {38, 27, 43, 3, 9, 82, 10};
        int[] array = {4, 3, 5, 2};

        System.out.println("原始数组：");
        for (int num : array) {
            System.out.print(num + " ");
        }
        System.out.println();
        mergeSort(array);

        System.out.println("\n排序后的数组：");
        for (int num : array) {
            System.out.print(num + " ");
        }

    }
}
